import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import { FilterRoutes } from '@/utils'
import Routes from './auth'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})



// 路由拦截
let isAddRouter = false;
router.beforeEach((to, from, next) => {
  if (!isAddRouter) {
    isAddRouter = true
    if (sessionStorage.getItem('token')) {
      FilterRoutes(sessionStorage.getItem('text'), Routes)
      store.commit('setRoutes', {
        list: Routes
      })
      router.addRoutes(Routes)
    }
    // 这一行就是解决问题的最终办法, 重新进当前路由
    next({ ...to, replace: true })
  } else {
    next()
  }
})


// const originalPush = VueRouter.prototype.push

// VueRouter.prototype.push = function push(location, onResolve, onReject) {

// if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)

// return originalPush.call(this, location).catch(err => err)

// }

export default router
